import Controller from './Controller';

export default class EditorController extends Controller {

	constructor( parent, object, property, config ) {
		if(config == null) config = {} ;
		super( parent, object, property, 'label', 'div', config );

		// this.$widget.innerHTML = object[property] ;

		this.editor = null ;
		this.$disable = this.$widget;
		this.flexPanel = null ;

		if(config.onInit != null)
			config.onInit(this,this.$widget) ;

		this.updateDisplay();

	}

	/**
	 * 引入vs编辑器
	 * @param editor
	 * @returns {EditorController}
	 */
	setEditor(editor){
		if(editor == null) return this ;

		const that = this ;
		editor.setValue(super.getValue()) ;
		this.editor = editor ;
		if(this.editor == null) return this ;

		editor.onDidChangeModelContent(event => {
			let _value = editor.getValue() ;
			if(_value != that.getValue()){
				that.setValue(editor.getValue()) ;
			}
		}) ;

		editor.onDidBlurEditorText(() => {
			that._callOnFinishChange() ;
		}) ;

		return this ;
	}

	updateDisplay() {
		if(this.editor != null) {
			let _value = super.getValue() ;
			//值一样时取消设置，不然会触发死循环
			if(_value == this.editor.getValue()) return this ;
			this.editor.setValue( super.getValue() );
		}
		return this;
	}

	addIcon(icon,title,func){
		if(this.flexPanel == null) {
			this.flexPanel = document.createElement( 'div' );
			this.flexPanel.classList.add( 'editorFlexPanel' );
			this.$widget.appendChild( this.flexPanel );
		}
		let iconDom = document.createElement( 'i' );
		iconDom.setAttribute("class",icon) ;
		if(title != null && title != "")
			iconDom.setAttribute("title",title) ;
		iconDom.classList.add( 'editorFlexItem' );
		const that = this ;
		iconDom.addEventListener( 'click', e => {
			if(func != null)
				func(e,that) ;
		} );
		this.flexPanel.appendChild( iconDom );
		return this ;
	}

	setHeight(height) {
		if(height == null) return this ;
		if(this.$widget == null) return this;
		this.$widget.style.height = height + "px" ;
		return this ;
	}

	setStyle(style){
		if(style == null || style == "") return this ;
		if(this.$widget == null) return this;
		this.$widget.setAttribute("style",style) ;
		return this ;
	}

	addClass(clazz){
		if(clazz == null || clazz == "") return this ;
		if(this.$widget == null) return this;
		this.$widget.classList.add(clazz) ;
		return this ;
	}

	removeClass(clazz){
		if(clazz == null || clazz == "") return this;
		if(this.$widget == null) return this;
		this.$widget.classList.remove(clazz) ;
		return this ;
	}

	destroy() {
		super.destroy() ;
		if(this.editor == null) return ;
		this.editor.dispose() ;
		this.editor = null ;
	}
}
